import { OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Logger } from '@nestjs/common';

const opt1 = {
  path: '/chat1',
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true
  }
};

@WebSocketGateway(opt1)
export class Chat1Gateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  private logger: Logger = new Logger('Chat1Gateway');

  @WebSocketServer()
  server: any;

  afterInit(server: any) {
    this.server = server;
  }

  handleConnection(client: any, ...args: any[]) {
    this.logger.log('新连接', args);
  }

  handleDisconnect(client: any) {
    this.logger.log('断开了连接', client);
  }

  @SubscribeMessage('debug')
  handleMessage(client: any, payload: any): any { // 用来测试
    this.logger.log('[debug]', payload);
    return {
      event: 'debug',
      data: payload
    };
  }

  @SubscribeMessage('m2s')
  onChatMsg(client: any, payload: any): any { // 用户发来的消息 直接转发
    var uid: String = payload.uid;
    if (uid != null && uid.length > 0) {
      this.server.emit('allMsg', payload);
    }
  }
}
